package cn.lingxue.lingapi.utils;

import cn.hutool.captcha.generator.RandomGenerator;
import cn.lingxue.lingapi.entity.Sms;
import com.cloopen.rest.sdk.BodyType;
import com.cloopen.rest.sdk.CCPRestSmsSDK;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * 短信验证码工具
 */
@Component
public class SMSUtil {


    @Resource
    private Sms sms;

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 发送短信验证码
     * @param phone
     * @return
     */
    public String sendSms(String phone){
        //生产环境请求地址：app.cloopen.com
        String serverIp = "app.cloopen.com";
        //请求端口
        String serverPort = "8883";
        //主账号,登陆云通讯网站后,可在控制台首页看到开发者主账号ACCOUNT SID和主账号令牌AUTH TOKEN
        String accountSId = sms.getAccountId();
        String accountToken = sms.getAuthToken();
        //请使用管理控制台中已创建应用的APPID
        String appId = sms.getAppId();
        CCPRestSmsSDK sdk = new CCPRestSmsSDK();
        sdk.init(serverIp, serverPort);
        sdk.setAccount(accountSId, accountToken);
        sdk.setAppId(appId);
        sdk.setBodyType(BodyType.Type_JSON);
        String to = phone;
        String templateId= "1";
        RandomGenerator randomUtil = new RandomGenerator("0123456789", 4);
        String randomNum = randomUtil.generate();
        Long expire = 2L;
        String[] datas = {randomNum, expire.toString()};
        HashMap<String, Object> result = sdk.sendTemplateSMS(to,templateId,datas);
        if("000000".equals(result.get("statusCode"))){
            redisTemplate.opsForValue().set(phone,randomNum);
            return randomNum;

        }else{
            return null;
        }
    }

    /**
     * 校验短信验证码
     * @param phone
     * @param code
     * @return
     */
    public boolean validSms(String phone,String code){
        if(Boolean.TRUE.equals(redisTemplate.hasKey(phone))){
            String redisCode = redisTemplate.opsForValue().get(phone);
            if (redisCode != null && redisCode.equals(code)) {
                redisTemplate.delete(phone);
                return true;
            }
        }
        return false ;
    }

}
